<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('证券列表')" />
	<style>
		/* 下拉框选中状态样式 */
		.dropdown-item.selected {
			background-color: #007bff !important;
			color: white !important;
		}
		
		/* 同步分时模态框样式 */
		.sync-modal {
			display: none;
			position: fixed;
			z-index: 1000;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0,0,0,0.5);
		}
		
		.sync-modal-content {
			background-color: #fefefe;
			margin: 15% auto;
			padding: 20px;
			border: 1px solid #888;
			width: 400px;
			border-radius: 5px;
		}
		
		.sync-modal-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20px;
		}
		
		.sync-modal-close {
			color: #aaa;
			font-size: 28px;
			font-weight: bold;
			cursor: pointer;
		}
		
		.sync-modal-close:hover {
			color: black;
		}
		
		.sync-options {
			margin-bottom: 20px;
		}
		
		.sync-option {
			margin-bottom: 10px;
		}
		
		.sync-option input[type="radio"] {
			margin-right: 8px;
		}
		
		.custom-date-input {
			margin-left: 20px;
			margin-top: 10px;
		}
		
		.custom-date-input input {
			padding: 5px;
			border: 1px solid #ccc;
			border-radius: 3px;
		}
	</style>
</head>
<body class="gray-bg">
<div class="container-div">
	<div class="row">
		<div class="col-sm-12 search-collapse">
			<form id="type-form">
				<div class="select-list">
					<ul>
						<li style="position: relative;">
							证券选择：<input type="text" id="securitySelect" placeholder="请输入名称或代码" style="width: 300px;" autocomplete="off"/>
							<input type="hidden" id="securitySymbol" name="securitySymbol"/>
							<div id="securityDropdown" style="display: none; position: absolute; top: 100%; left: 80px; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; z-index: 1000; width: 300px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"></div>
						</li>
						<li>
							证券交易所：<select name="securityExchange" th:with="type=${@dict.getType('security_exchange')}">
							<option value="">所有</option>
							<option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
						</select>
						<li>
							证券类型：<select name="securityType" th:with="type=${@dict.getType('security_type')}">
							<option value="">所有</option>
							<option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
						</select>
						</li>
						<li>
							股票板块：<select name="stockBoard" th:with="type=${@dict.getType('stock_board')}">
							<option value="">所有</option>
							<option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
						</select>
						</li>
						<li>
							<a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
							<a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
						</li>
					</ul>
				</div>
			</form>
		</div>

		<div class="btn-group-sm" id="toolbar" role="group">
			<a class="btn btn-success" onclick="$.operate.sync()">
				<i class="fa fa-plus"></i> 同步
			</a>
			<a class="btn btn-primary single disabled" onclick="$.operate.edit()" shiro:hasPermission="galaxy:user:edit">
				<i class="fa fa-edit"></i> 修改
			</a>
			<a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="galaxy:user:remove">
				<i class="fa fa-remove"></i> 删除
			</a>
			<a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="galaxy:user:export">
				<i class="fa fa-download"></i> 导出
			</a>
		</div>

		<div class="col-sm-12 select-table table-striped">
			<table id="bootstrap-table"></table>
		</div>
	</div>
</div>

<!-- 同步分时模态框 -->
<div id="syncModal" class="sync-modal">
	<div class="sync-modal-content">
		<div class="sync-modal-header">
			<h3 id="syncModalTitle">同步分时数据</h3>
			<span class="sync-modal-close" onclick="closeSyncModal()">&times;</span>
		</div>
		<div class="sync-options">
			<div class="sync-option">
				<input type="radio" id="option1d" name="syncPeriod" value="1d">
				<label for="option1d">1天</label>
			</div>
			<div class="sync-option">
				<input type="radio" id="option5d" name="syncPeriod" value="5d">
				<label for="option5d">5天</label>
			</div>
			<div class="sync-option">
				<input type="radio" id="option10d" name="syncPeriod" value="10d">
				<label for="option10d">10天</label>
			</div>
			<div class="sync-option">
				<input type="radio" id="option1m" name="syncPeriod" value="1m">
				<label for="option1m">1月</label>
			</div>
			<div class="sync-option">
				<input type="radio" id="option3m" name="syncPeriod" value="3m">
				<label for="option3m">3月</label>
			</div>
			<div class="sync-option">
				<input type="radio" id="optionCustom" name="syncPeriod" value="custom">
				<label for="optionCustom">自定义</label>
				<div class="custom-date-input" id="customDateInput" style="display: none;">
					<label>开始日期：</label>
					<input type="date" id="startDate">
					<br><br>
					<label>结束日期：</label>
					<input type="date" id="endDate">
				</div>
			</div>
		</div>
		<div style="text-align: right;">
			<button type="button" class="btn btn-default" onclick="closeSyncModal()">取消</button>
			<button type="button" class="btn btn-primary" onclick="confirmSync()">确定</button>
		</div>
	</div>
</div>

<th:block th:include="include :: footer" />
<script th:inline="javascript">
	var typeDatas = [[${@dict.getType('security_type')}]];
	var exchangeDatas = [[${@dict.getType('security_exchange')}]];
	var prefix = ctx + "security";
	
	// 证券列表数据
	var securitiesList = [];
	var currentSelectedIndex = -1; // 当前选中的下拉项索引
	
	// 同步分时相关变量
	var currentSyncSymbol = '';
	var currentSyncName = '';

	$(function() {
		// 加载证券列表
		loadSecuritiesList();
		
		// 绑定搜索框事件
		$("#securitySelect").on('input', function() {
			var searchText = $(this).val().toLowerCase();
			
			// 如果输入框包含" - "，说明用户可能是在已选择的证券基础上继续输入
			// 提取最后一部分作为搜索文本
			if (searchText.includes(' - ')) {
				var parts = searchText.split(' - ');
				if (parts.length > 1) {
					// 取最后一部分作为搜索文本
					searchText = parts[parts.length - 1].toLowerCase();
				}
			}
			
			if (searchText.length > 0) {
				showSecurityDropdown(searchText);
			} else {
				hideSecurityDropdown();
			}
		});
		
		// 添加键盘事件处理
		$("#securitySelect").on('keydown', function(e) {
			var dropdown = $("#securityDropdown");
			var items = dropdown.find('.dropdown-item');
			
			if (items.length === 0) {
				return; // 没有下拉项时不处理
			}
			
			switch(e.keyCode) {
				case 38: // 上箭头
					e.preventDefault();
					currentSelectedIndex = Math.max(0, currentSelectedIndex - 1);
					updateSelection(items);
					break;
				case 40: // 下箭头
					e.preventDefault();
					currentSelectedIndex = Math.min(items.length - 1, currentSelectedIndex + 1);
					updateSelection(items);
					break;
				case 13: // 回车
					e.preventDefault();
					if (currentSelectedIndex >= 0 && currentSelectedIndex < items.length) {
						items.eq(currentSelectedIndex).click();
					}
					break;
				case 27: // ESC
					e.preventDefault();
					hideSecurityDropdown();
					currentSelectedIndex = -1;
					break;
			}
		});
		
		// 添加键盘事件作为备用（用于搜索）
		$("#securitySelect").on('keyup', function(e) {
			// 如果不是导航键，则进行搜索
			if (![38, 40, 13, 27].includes(e.keyCode)) {
				var searchText = $(this).val().toLowerCase();
				
				// 如果输入框包含" - "，说明用户可能是在已选择的证券基础上继续输入
				// 提取最后一部分作为搜索文本
				if (searchText.includes(' - ')) {
					var parts = searchText.split(' - ');
					if (parts.length > 1) {
						// 取最后一部分作为搜索文本
						searchText = parts[parts.length - 1].toLowerCase();
					}
				}
				
				if (searchText.length > 0) {
					showSecurityDropdown(searchText);
				} else {
					hideSecurityDropdown();
				}
				currentSelectedIndex = -1; // 重置选中索引
			}
		});
		
		// 点击其他地方隐藏下拉框
		$(document).click(function(e) {
			if (!$(e.target).closest('#securitySelect, #securityDropdown').length) {
				hideSecurityDropdown();
			}
		});
		
		// 监听自定义日期选择
		$('input[name="syncPeriod"]').change(function() {
			if ($(this).val() === 'custom') {
				$('#customDateInput').show();
			} else {
				$('#customDateInput').hide();
			}
		});
		
		var options = {
			url: prefix + "/list",
			createUrl: prefix + "/syncList",
			updateUrl: prefix + "/edit/{id}",
			removeUrl: prefix + "/remove",
			exportUrl: prefix + "/export",
			// sortName: "userId",
			// sortOrder: "asc",
			modalName: "证券",
			columns: [{
				checkbox: true
			},
				{
					field: 'type',
					title: '类型',
					align: 'center',
					formatter: function(value, row, index) {
						return $.table.selectDictLabel(typeDatas, value);
					}
				},
				{
					field: 'exchange',
					title: '交易所',
					align: 'center',
					formatter: function(value, row, index) {
						return $.table.selectDictLabel(exchangeDatas, value);
					}
				},
				{
					field: 'code',
					title: '代码',
					sortable: true
				},
				{
					field: 'name',
					title: '名称',
					sortable: true
				},
				{
					field: 'latestPrice',
					title: '最新价',
					sortable: true
				},
				{
					field: 'riseFallAmount',
					title: '涨跌额',
					sortable: true
				},
				{
					field: 'riseFallAmountPercentage',
					title: '涨跌幅%',
					sortable: true
				},
				{
					field: 'highestPrice',
					title: '最高价',
					sortable: true
				},
				{
					field: 'lowestPrice',
					title: '最低价',
					sortable: true
				},
				{
					field: 'volume',
					title: '成交量/手',
					sortable: true
				},
				{
					field: 'turnover',
					title: '成交额/万',
					sortable: true
				},
				// {
				// 	field: 'createTime',
				// 	title: '创建时间',
				// 	sortable: true
				// },
				{
					field: 'updateTime',
					title: '更新时间',
					sortable: true
				},
				{
					title: '操作',
					align: 'center',
					formatter: function(value, row, index) {
						var actions = [];
						actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="syncSecurity(\'' + row.symbol + '\', \'' + row.name + '\')"><i class="fa fa-refresh"></i>同步</a> ');
						actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="syncTimeShare(\'' + row.symbol + '\', \'' + row.name + '\')"><i class="fa fa-clock-o"></i>同步分时</a>');
						return actions.join('');
					}
				}]
		};
		$.table.init(options);
	});

	
	// 加载证券列表
	function loadSecuritiesList() {
		$.ajax({
			url: ctx + "security/securities",
			type: "GET",
			dataType: 'json',
			success: function(data) {
				if (data.code === 0 && data.data) {
					securitiesList = data.data;
					console.log("成功加载证券列表，数量:", securitiesList.length);
				} else {
					console.error("获取证券列表失败:", data.msg);
				}
			},
			error: function(xhr, status, error) {
				console.error("获取证券列表失败:", error);
			}
		});
	}
	
	// 显示证券下拉框
	function showSecurityDropdown(searchText) {
		var dropdown = $("#securityDropdown");
		dropdown.empty();
		
		var filteredSecurities = securitiesList.filter(function(security) {
			var code = (security.code || '').toLowerCase();
			var name = (security.name || '').toLowerCase();
			var fullCode = (security.exchange + security.code).toLowerCase();
			var search = searchText.toLowerCase();
			
			return code.includes(search) || name.includes(search) || fullCode.includes(search);
		});
		
		if (filteredSecurities.length > 0) {
			filteredSecurities.forEach(function(security) {
				var displayCode = security.exchange + security.code;
				var displayText = displayCode + " - " + security.name;
				
				var item = $('<div class="dropdown-item" style="padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #eee;">' +
					'<strong>' + displayCode + '</strong> - ' + security.name + '</div>');
				
				item.hover(
					function() { $(this).css('background-color', '#f5f5f5'); },
					function() { $(this).css('background-color', 'white'); }
				);
				
				item.click(function() {
					$("#securitySelect").val(displayText);
					$("#securitySymbol").val(displayCode); // 设置隐藏字段为纯证券代码
					hideSecurityDropdown();
				});
				
				dropdown.append(item);
			});
			
			dropdown.show();
		} else {
			dropdown.hide();
		}
	}
	
	// 隐藏证券下拉框
	function hideSecurityDropdown() {
		$("#securityDropdown").hide();
		currentSelectedIndex = -1;
	}
	
	// 更新选中项的高亮显示
	function updateSelection(items) {
		items.removeClass('selected');
		if (currentSelectedIndex >= 0 && currentSelectedIndex < items.length) {
			items.eq(currentSelectedIndex).addClass('selected');
		}
	}
	
	// 同步证券数据
	function syncSecurity(symbol, name) {
		if (confirm('确定要同步证券 "' + name + '" 的数据吗？')) {
			// 发送同步请求
			$.ajax({
				url: ctx + "security/sync",
				type: "POST",
				data: {
					symbol: symbol
				},
				dataType: 'json',
				success: function(data) {
					if (data.code === 0) {
						alert('同步成功');
						// 刷新表格
						$('#bootstrap-table').bootstrapTable('refresh');
					} else {
						alert('同步失败：' + data.msg);
					}
				},
				error: function(xhr, status, error) {
					alert('同步失败：' + error);
				}
			});
		}
	}
	
	// 同步分时数据
	function syncTimeShare(symbol, name) {
		currentSyncSymbol = symbol;
		currentSyncName = name;
		$('#syncModalTitle').text('同步分时数据 - ' + name);
		$('#syncModal').show();
		
		// 重置选择
		$('input[name="syncPeriod"]').prop('checked', false);
		$('#customDateInput').hide();
	}
	
	// 关闭同步模态框
	function closeSyncModal() {
		$('#syncModal').hide();
	}
	
	// 确认同步
	function confirmSync() {
		var selectedPeriod = $('input[name="syncPeriod"]:checked').val();
		
		if (!selectedPeriod) {
			alert('请选择同步周期');
			return;
		}
		
		var syncData = {
			symbol: currentSyncSymbol,
			name: currentSyncName
		};
		
		// 根据选择的周期计算开始和结束日期
		var today = new Date();
		var startDate, endDate;
		
		if (selectedPeriod === 'custom') {
			// 自定义日期
			startDate = $('#startDate').val();
			endDate = $('#endDate').val();
			
			if (!startDate || !endDate) {
				alert('请选择开始日期和结束日期');
				return;
			}
			
			if (new Date(startDate) > new Date(endDate)) {
				alert('开始日期不能大于结束日期');
				return;
			}
		} else {
			// 根据周期计算日期
			endDate = today.toISOString().split('T')[0]; // 今天
			
			switch(selectedPeriod) {
				case '1d':
					startDate = endDate;
					break;
				case '5d':
					var fiveDaysAgo = new Date(today);
					fiveDaysAgo.setDate(today.getDate() - 5);
					startDate = fiveDaysAgo.toISOString().split('T')[0];
					break;
				case '10d':
					var tenDaysAgo = new Date(today);
					tenDaysAgo.setDate(today.getDate() - 10);
					startDate = tenDaysAgo.toISOString().split('T')[0];
					break;
				case '1m':
					var oneMonthAgo = new Date(today);
					oneMonthAgo.setMonth(today.getMonth() - 1);
					startDate = oneMonthAgo.toISOString().split('T')[0];
					break;
				case '3m':
					var threeMonthsAgo = new Date(today);
					threeMonthsAgo.setMonth(today.getMonth() - 3);
					startDate = threeMonthsAgo.toISOString().split('T')[0];
					break;
				default:
					alert('无效的同步周期');
					return;
			}
		}
		
		syncData.startDate = startDate;
		syncData.endDate = endDate;
		
		// 发送同步请求
		$.ajax({
			url: ctx + "security/time-share/sync",
			type: "POST",
			data: syncData,
			dataType: 'json',
			success: function(data) {
				if (data.code === 0) {
					alert('同步成功');
					closeSyncModal();
					// 刷新表格
					$('#bootstrap-table').bootstrapTable('refresh');
				} else {
					alert('同步失败：' + data.msg);
				}
			},
			error: function(xhr, status, error) {
				alert('同步失败：' + error);
			}
		});
	}
</script>
</body>
</html>